<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        :elements="elements"
        @submit="handleSearch"
        @reset="handleReset"
      >
        <Button icon="add" type="plain" @click="handleAdd">新增</Button>
        <Button
          icon="icon-daochu"
          :btn-loading="dcLoading"
          @click="handleDealExcel(2)"
          >导出</Button
        >
      </FilterForm>
    </Container>
    <Container height="fill">
      <div class="wraper">
        <Table
          :columns="tableColumns"
          :loading="tableLoading"
          :data="tableData"
          :pagination="{
            total: total,
            current: currentPage,
            pageSize: pageSize,
          }"
          @paginationChange="pageChange"
          @rowSelection="handleSelection"
        >
          <template #caozuo="{ row }">
            <!-- <Tooltip content="编辑" icon="edit" @click="handleEdit(row)" /> -->
            <Tooltip v-if="row.source==='本系统'" content="删除" icon="delete" @click="handleDelete(row)" />
          </template>
        </Table>
      </div>
      <!-- 新增、编辑 -->
      <Drawer
        ref="drawerRef"
        :title="title"
        :visible.sync="showDrawer"
        width="420px"
        :footer-btns="[
          {
            text: '确认',
            type: 'primary',
            loading: qrLoading,
            trigger: 'submit',
          },
          {
            text: '取消',
            type: 'info',
            trigger: 'cancel',
          },
        ]"
        @submit="handleSubmit"
        @cancel="showDrawer = false"
      >
        <el-form
          v-if="showDrawer"
          ref="drawerForm"
          :model="drawerForm"
          :rules="drawerRules"
          label-width="120px"
          size="mini"
          class="demo-drawerForm"
        >
          <el-form-item label="统计项目编码：" prop="projectCode">
            <el-input
              v-model.trim="drawerForm.projectCode"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="统计项目名称：" prop="projectName">
            <el-input
              v-model.trim="drawerForm.projectName"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="来源：" prop="source">
            <el-select
              v-model="drawerForm.source"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in elements[1].options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注：">
            <el-input
              v-model.trim="drawerForm.remark"
              placeholder="请输入"
              type="textarea"
              :rows="5"
              maxlength="50"
              clearable
            />
          </el-form-item>
        </el-form>
      </Drawer>
    </Container>
  </ContainerGroup>
</template>
<script>
import {
  listByCodeOrName,
  listProjectTargetAdministrationPull,
  insertProject,
  deleteProject,
  exportProject
} from '@/api/targetManagement'
export default {
  data() {
    return {
      dcLoading: false,
      qrLoading: false,
      btnType: 1,
      optionList: [],
      drawerForm: {
        projectCode: "",
        projectName: "",
        source: "",
        remark: ""
      },
      drawerRules: {
        projectCode: [
          { required: true, message: "请输入统计项目编码", trigger: "blur" },
        ],
        projectName: [
          { required: true, message: "请输入统计项目名称", trigger: "blur" },
        ],
        source: [
          { required: true, message: "请选择来源", trigger: "change" },
        ]
      },
      darawerLoading: false,
      showDrawer: false,
      title: "",
      fileList: [],
      importLoading: false,
      tableColumns: [
        {
          title: "统计项目编码",
          dataIndex: "projectCode",
        },
        {
          title: "统计项目名称",
          dataIndex: "projectName",
        },
        {
          title: "来源",
          dataIndex: "source",
        },
        {
          title: "备注",
          dataIndex: "remark",
        },
        {
          title: "操作",
          dataIndex: "caozuo",
          type: "otherTag",
          width: 160,
        },
      ],
      total: 0,
      pageSize: 100,
      currentPage: 1,
      tableLoading: false,
      tableData: [],
      newCondition: {},
      elements: [
        {
          label: "综合搜索",
          type: "input",
          key: "nameOrNumber",
          value: "",
          placeholder: "请输入统计项目编码/统计项目名称",
          width: 240,
        },
        {
          label: "来源",
          key: "source",
          type: "select",
          hideSelectAll: true,
          itemValue: 'id',
          itemLabel: 'name',
          options: [],
          value: '',
        },
      ],
      currentRow: {},
      selections: [],
    };
  },
  created() {
    this.getSelect();
  },
  methods: {
    handleSelection(row) {
      this.selections = row;
    },
    handleDealExcel() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        nameOrNumber: this.$refs.filterForm.getParms()?.nameOrNumber,
        source: this.$refs.filterForm.getParms()?.source,
        ids: this.selections.map((item) => item.id),
      };
      this.dcLoading = true;
      exportProject(params).then((res) => {
        this.dcLoading = false;
        this.$utils.downloadFileFun(res, "统计项目.xls");
      });
    },
    getSelect() {
      //类别
      listProjectTargetAdministrationPull({
        code: 'sys_source'
      }).then((res) => {
        if (res.code === 200) {
          this.elements[1].options = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    handleSubmit() {
      this.$refs["drawerForm"].validate((valid) => {
        if (/[\u4e00-\u9fa5]+/.test(this.drawerForm.projectCode)) {
          this.$message.warning("核算单元编码不能包含中文");
          return;
        }

        if (valid) {
          const param = {
            ...this.drawerForm
          };

          if (this.btnType === 2) {
            // 编辑
            param.id = this.currentRow?.id;
          }
          this.qrLoading = true;
          insertProject(param).then((res) => {
            this.qrLoading = false;
            if (res.code === 200) {
              this.getData();
              this.showDrawer = false;
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          }).catch(()=>{
            this.qrLoading = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查询
    handleSearch(value) {
      this.newCondition = value;
      this.currentPage = 1;
      this.getData();
    },
    // 重置
    handleReset(val) {
      this.handleSearch(val);
    },
    handleEdit(row) {
      // 编辑
      this.currentRow = row;
      this.btnType = 2;
      this.title = "编辑";
      this.handleSetForm(row);
      this.showDrawer = true;
    },
    handleSetForm(row) {
      this.$handleSetForm(this.drawerForm, 1, row);
    },
    handleDelete(row) {
      // 删除
      this.$ckConfirm({
        content: "此操作将删除该条记录，并无法恢复， 是否继续?",
        title: "提示",
        okFn: (res) => {
          deleteProject({
            id: row.id,
          }).then((res) => {
            if (res.code === 200) {
              this.currentPage = 1;
              this.getData();
              this.$message.success(res.message);
            } else {
              this.$message.error(res.message);
            }
          });
        },
        cancelFn: (res) => {
          console.log("取消");
        },
      });
    },
    handleAdd() {
      this.btnType = 1;
      this.title = "添加";
      this.$handleSetForm(this.drawerForm, 0);
      this.drawerForm.status = "1";
      this.showDrawer = true;
    },
    getData() {
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        nameOrNumber: this.newCondition.nameOrNumber,
        source: this.newCondition.source,
      };
      this.tableLoading = true;
      listByCodeOrName(params)
        .then((res) => {
          this.tableLoading = false;
          if (res.code === 200) {
            this.tableData = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    pageChange(payload) {
      this.currentPage = payload.current;
      this.pageSize = payload.pageSize;
      this.getData();
    },
  },
};
</script>
<style lang="less" scoped>
.wraper {
  display: flex;
  height: 100%;
  overflow: hidden;
  .upload-demo {
    .buttons {
      margin: 0px 5px;
      height: 27px;
      margin-top: -1px;
    }
  }
}
</style>
